<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>请求超时与网络异常</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>

    const btn=document.querySelector('button')
    btn.addEventListener("click", function () {
        const xhr=new XMLHttpRequest()
        xhr.open('GET','http://localhost:8000/timeout')

        //超时设置2s
        xhr.timeout=2000;

        //超时回调
        xhr.addEventListener('timeout',function (){
            alert('超时,请重试')
            }
        )

        //网络异常回调
        xhr.addEventListener('error',function () {
            alert('你的网络似乎出了点问题')
        })


        xhr.send()
        xhr.onreadystatechange=function () {
            if (xhr.readyState===4){
                if (xhr.status>=200&&xhr.status<300){
                    document.querySelector('div').innerHTML=`${xhr.response}`
                }
            }

        }
    })
</script>
</body>
</html>